import time, json, requests
import matplotlib.pyplot as plt
import numpy as np

# 抓取腾讯疫情实时json数据
url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d' % int(time.time() * 1000)
origindatas = requests.get(url=url)
print("origindata:" + origindatas.json()['data'])  # 将抓取的数据转换为json格式并获取里面的数据
print("status code:" + str(origindatas.status_code))  # 获取数据的返回状态
data = json.loads(requests.get(url=url).json()['data'])  
print("datas:")
print(str(data))
print(data.keys())

# 统计省份信息(34个省份 湖北 广东 河南 浙江 湖南 安徽....)
c_datas = data['areaTree'][0]['children']
print(len(c_datas))
for item in c_datas:
    print(item['name'], end=" ")  # 获取每个省的省名称
else:
    print("\n")

# 显示陕西省的数据
shanxi = c_datas[1]['children']
for data in shanxi:
    print(data)
# 解析json数据
total_datas = {}
shanxi_datas = {}
for data in c_datas:
    if data['name'] not in total_datas:
        total_datas.update({data['name']: 0})
    for province_data in data['children']:  # 获取每个省份确认的数据
        total_datas[data['name']] += int(province_data['total']['confirm'])
print(total_datas)
# 以陕西省为例获取每个市的数据
for sx in shanxi:
    print(sx['name'] + "\n")
    print(int(sx['total']['confirm']))
    shanxi_datas[sx['name']] = int(sx['total']['confirm'])
print(shanxi_datas)

names = shanxi_datas.keys()
nums = shanxi_datas.values()

# 绘制条形图
plt.figure(figsize=[10, 6])
plt.bar(names, nums, width=0.3, color='green')
# 设置标题
plt.xlabel("地区", fontproperties='SimHei', rotation=90, size=12)
plt.ylabel("人数", fontproperties='SimHei', size=12)
plt.title("陕西省各市疫情数据对比", fontproperties='SimHei', size=20)
plt.xticks(list(names), fontproperties='SimHei', rotation=-45, size=10)
# 每个图形上显示数据
for a, b in zip(list(names), list(nums)):
    plt.text(a, b, b, ha='center', va='bottom', size=6)
plt.show()